#pragma once

#include "TextBox.h"

vector<TextBox *> TextBox::lst;
TextBox* TextBox::ActiveTextBox = NULL;
HHOOK TextBox::hook;

TextBox::TextBox(int x, int y, int width)
{
    if (!hook)
    {
        hook = SetWindowsHookEx(WH_GETMESSAGE, TextBox::GetMsgProc, GetModuleHandle(NULL), GetCurrentThreadId() );
    }
	lst.push_back(this);

    ActiveColor = ACTIVE_COLOR;
    NormalColor = NORMAL_COLOR;
    TextColor  = TEXT_COLOR;

	m_Rect.left = x;
	m_Rect.top = y;
	m_Rect.right = m_Rect.left + width;
	m_Rect.bottom = m_Rect.top + 22;
    strAction = "";
}

TextBox::~TextBox()
{		
    //fix
    if (this == ActiveTextBox) ActiveTextBox = NULL;
    //
	vector<TextBox*>::iterator it = std::find(lst.begin(),lst.end(), this);
	if (it != lst.end()) lst.erase(it);
}

LRESULT CALLBACK TextBox::GetMsgProc( int code, WPARAM wParam, LPARAM lParam )
{
    MSG *msg = (MSG *)lParam;
    if (msg->message == WM_CHAR)
    {        
        if (ActiveTextBox != NULL)
        {
            char ch = (char)msg->wParam;
            if (ch == 8)
            {
                ActiveTextBox->strAction = ActiveTextBox->strAction.substr(0,ActiveTextBox->strAction.length()-1);
            }
            else
            {
                ActiveTextBox->strAction += (char)msg->wParam;
            }
        }
    }
    return CallNextHookEx(hook, code, wParam, lParam);
}

void TextBox::OnDraw()
{
    dbInk(ActiveTextBox == this ? ActiveColor : NormalColor, RGB(64,64,64));
    dbBox(m_Rect.left, m_Rect.top, m_Rect.right, m_Rect.bottom);        
    dbInk(TextColor, RGB(64,64,64));
    dbText(m_Rect.left + 2, m_Rect.top + 2, (char*)strAction.c_str());
}

void TextBox::OnClick( int x, int y )
{
    ActiveTextBox = this;
}

RECT* TextBox::GetRect()
{
    return &m_Rect;
}

void TextBox::OnHover( int x, int y )
{
    
}

TGDKSprite* TextBox::GetMainSprite()
{
    return NULL;
}

void TextBox::OnLeave()
{
    
}

void TextBox::SetPosition( int x, int y )
{
    int w = GetWidth();
    int h = GetHeight();
    m_Rect.left = x;
    m_Rect.top  = y;
    m_Rect.right = x + w;
    m_Rect.bottom = y + h;
}
